//
//  XBSegmentedControl.m
//  FamilyDoctor
//
//  Created by xxb on 2017/11/15.
//  Copyright © 2017年 zoenet. All rights reserved.
//

#import "XBSegmentedControl.h"
#import "XBSegmentedControlCell.h"
#import "XBSegmentedControlHeader.h"

#define BottomLineHeight 1

@interface XBSegmentedControl ()<UICollectionViewDelegate, UICollectionViewDataSource>

@property (nonatomic, strong) UICollectionView *collection;
@property (nonatomic, strong) UIView *lineView;
@property (nonatomic, strong) UIView *indicatorView;//指示view
@property (nonatomic, strong) NSMutableArray *titleFrameArray;//title的frame
@property (nonatomic, strong) NSMutableArray *cellSizeArray;//cell的宽度

@end

@implementation XBSegmentedControl

-(instancetype)initWithFrame:(CGRect)frame{
    self = [super initWithFrame:frame];
    if(self){
        self.backgroundColor = [UIColor whiteColor];
        [self addSubview:self.collection];
        [self addSubview:self.lineView];
    }
    return self;
}

#pragma mark - delegate

#pragma mark -collectionView

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section{
    return self.dataSource.count;
}

- (__kindof UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{
    XBSegmentedControlCell *cell;
    if(indexPath.row == 0){
        cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"FirstCell" forIndexPath:indexPath];
    }else if(indexPath.row == self.dataSource.count - 1){
        cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"LastCell" forIndexPath:indexPath];
    }else{
        cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"MiddleCell" forIndexPath:indexPath];
    }
    cell.noBlodWhenSelected = self.noBlodWhenSelected;
    cell.textColorSelected = self.textColorSelected;
    cell.titleLabel.text = self.dataSource[indexPath.row];
    cell.labelFrame = [self.titleFrameArray[indexPath.row] CGRectValue];
    if(self.selectedRow == indexPath.row){
        cell.selected = YES;
        [collectionView selectItemAtIndexPath:indexPath animated:NO scrollPosition:UICollectionViewScrollPositionNone];
        [self indicatorViewChg];
    }else{
        cell.selected = NO;
    }
    return cell;
}

- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath{
    XBSegmentedControlCell *cell = (XBSegmentedControlCell*)[collectionView cellForItemAtIndexPath:indexPath];
    cell.selected = YES;
    self.selectedRow = indexPath.row;
    [self indicatorViewChg];
    if([self.delegate respondsToSelector:@selector(didSelectAtIndex:)]){
        [self.delegate didSelectAtIndex:indexPath.row];
    }
}

- (void)collectionView:(UICollectionView *)collectionView didDeselectItemAtIndexPath:(NSIndexPath *)indexPath{
    XBSegmentedControlCell *cell = (XBSegmentedControlCell*)[collectionView cellForItemAtIndexPath:indexPath];
    cell.selected = NO;
}

#pragma mark -设置每个item的size

- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath{
    return [self.cellSizeArray[indexPath.row] CGSizeValue];
}

#pragma mark - Event

-(void)indicatorViewChg{
    UICollectionViewLayoutAttributes *attributes = [self.collection layoutAttributesForItemAtIndexPath:[NSIndexPath indexPathForRow:self.selectedRow inSection:0]];
    
    CGFloat x = attributes.frame.origin.x + [self.titleFrameArray[self.selectedRow] CGRectValue].origin.x;
    if(CGRectIsEmpty(self.indicatorView.frame)){
        self.indicatorView.frame = CGRectMake(x, self.collection.frame.size.height - IndicatorHeight, [self.titleFrameArray[self.selectedRow] CGRectValue].size.width, IndicatorHeight);
    }else{
        //动画
        [UIView animateWithDuration:0.2 animations:^{
            CGRect frame = self.indicatorView.frame;
            frame.origin.x = x;
            frame.size.width = [self.titleFrameArray[self.selectedRow] CGRectValue].size.width;
            self.indicatorView.frame = frame;
        } completion:^(BOOL finished) {
        }];
    }
}

-(void)reloadData{
    [self.collection reloadData];
}

-(void)setSelectedSegmentIndex:(NSInteger)index{
    if(self.collection.visibleCells.count == 0){
        return;
    }

    NSIndexPath *indexPath = [NSIndexPath indexPathForRow:index inSection:0];
    [self.collection selectItemAtIndexPath:indexPath animated:NO scrollPosition:UICollectionViewScrollPositionNone];
    XBSegmentedControlCell *cell = (XBSegmentedControlCell*)[self.collection cellForItemAtIndexPath:indexPath];
    cell.selected = YES;
    self.selectedRow = index;
    [self indicatorViewChg];
    
    //不在当前视图
    CGFloat pY = 0;//中间点p的位置
    for(NSInteger i = 0 ; i <= index; i++){
        if(i == index){
            pY += [self.cellSizeArray[i] CGSizeValue].width / 2;
        }else{
            pY += [self.cellSizeArray[i] CGSizeValue].width;
        }
    }
    CGFloat halfCollectionWidth = self.collection.frame.size.width / 2;
    CGFloat contentWidth = 0;
    for(NSInteger i = 0; i < self.cellSizeArray.count; i++){
        contentWidth += [self.cellSizeArray[i] CGSizeValue].width;
    }
    
    if(pY < halfCollectionWidth){
        //contentOffset.x可以设置为0的情况
        [self.collection setContentOffset:CGPointMake(0, 0) animated:YES];
    }else if(contentWidth - pY < halfCollectionWidth){
        //contentOffset.x可以设置contentSize.width-collectionView.frameWdith情况
        [self.collection setContentOffset:CGPointMake(contentWidth - self.collection.frame.size.width, 0) animated:YES];
    }else{
        [self.collection setContentOffset:CGPointMake(pY - halfCollectionWidth, 0) animated:YES];
    }
}

- (void)setShowLineView:(BOOL)showLineView {
    self.lineView.hidden = !showLineView;
}

#pragma mark - property

-(void)setDataSource:(NSArray *)dataSource{
    _dataSource = dataSource;
    
    self.cellSizeArray = [[NSMutableArray alloc] initWithCapacity:dataSource.count];
    self.titleFrameArray = [[NSMutableArray alloc] initWithCapacity:dataSource.count];
    
    CGFloat collectionWidth = 0;
    for(NSInteger i = 0; i < _dataSource.count; i++){
        NSString *title = _dataSource[i];
        CGFloat width = [title sizeWithAttributes:@{NSFontAttributeName:[UIFont systemFontOfSize:FontSize]}].width;
        width = ceil(width) + 4;
        CGFloat y = (self.frame.size.height - FontSize) / 2;
        if(i == 0){
            collectionWidth += Margin + width + CellSpacing;
            self.cellSizeArray[i] = [NSValue valueWithCGSize:CGSizeMake(Margin + width + CellSpacing, self.frame.size.height)];
            self.titleFrameArray[i] = [NSValue valueWithCGRect:CGRectMake(Margin, y, width, FontSize)];
        }else if(i == _dataSource.count - 1){
            collectionWidth += width + Margin;
            self.cellSizeArray[i] = [NSValue valueWithCGSize:CGSizeMake(width + Margin, self.frame.size.height)];
            self.titleFrameArray[i] = [NSValue valueWithCGRect:CGRectMake(0, y, width, FontSize)];
        }else{
            collectionWidth += width + CellSpacing;
            self.cellSizeArray[i] = [NSValue valueWithCGSize:CGSizeMake(width + CellSpacing, self.frame.size.height)];
            self.titleFrameArray[i] = [NSValue valueWithCGRect:CGRectMake(0, y, width, FontSize)];
        }
    }
    
    if(self.centerWhenNotEnoughData){
        if(collectionWidth < self.frame.size.width){
            CGRect frame = self.collection.frame;
            frame.size.width = collectionWidth;
            frame.origin.x = (self.frame.size.width - collectionWidth) / 2;
            self.collection.frame = frame;
            frame = self.lineView.frame;
            frame.size.width = collectionWidth;
            frame.origin.x = self.collection.frame.origin.x;
            self.lineView.frame = frame;
        }else{
            CGRect frame = self.collection.frame;
            frame.size.width = self.frame.size.width;
            frame.origin.x = 0;
            self.collection.frame = frame;
            frame = self.lineView.frame;
            frame.size.width = collectionWidth;
            frame.origin.x = self.collection.frame.origin.x;
            self.lineView.frame = frame;
        }
    }
}

-(UICollectionView *)collection{
    if(!_collection){
        UICollectionViewFlowLayout *layout = [[UICollectionViewFlowLayout alloc] init];
        layout.scrollDirection = UICollectionViewScrollDirectionHorizontal;
        layout.minimumLineSpacing = 0;
        layout.minimumInteritemSpacing = 0;
        layout.sectionInset = UIEdgeInsetsZero;
        _collection = [[UICollectionView alloc] initWithFrame:CGRectMake(0, 0, CGRectGetWidth(self.frame), CGRectGetHeight(self.frame) - BottomLineHeight) collectionViewLayout:layout];
        _collection.showsVerticalScrollIndicator = NO;
        _collection.showsHorizontalScrollIndicator = NO;
        _collection.backgroundColor = [UIColor clearColor];
        _collection.delegate = self;
        _collection.dataSource = self;
        [_collection registerClass:[XBSegmentedControlCell class] forCellWithReuseIdentifier:@"MiddleCell"];
        [_collection registerClass:[XBSegmentedControlCell class] forCellWithReuseIdentifier:@"FirstCell"];
        [_collection registerClass:[XBSegmentedControlCell class] forCellWithReuseIdentifier:@"LastCell"];
    }
    return _collection;
}

-(UIView *)lineView{
    if(!_lineView){
        _lineView = [[UIView alloc] initWithFrame:CGRectMake(0, CGRectGetMaxY(self.collection.frame), CGRectGetWidth(self.frame), BottomLineHeight)];
        _lineView.backgroundColor = BottomLineColor;
    }
    return _lineView;
}

-(UIView *)indicatorView{
    if(!_indicatorView){
        _indicatorView = [[UIView alloc] init];
        _indicatorView.backgroundColor = IndicatorColor;
        [self.collection addSubview:_indicatorView];
    }
    return _indicatorView;
}
@end
